<?php

namespace App\Events;

use App\Models\Phone;
use App\Services\PlivoService;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class BuyPhone
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    protected $plivoService;

    public function __construct()
    {
        $plivoService = new PlivoService;
        $this->plivoService = $plivoService;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }

    //购买电话
    public function buyNumber(){
        $res = DB::table('phone_settings')->where('status',1)->first();
        if (!app()->environment('production')) {
            $number = '+'.str_pad(random_int(1, 99999999), 4, 0, STR_PAD_LEFT);
            $data['friendly_name'] = $number;
            $data['phone_number'] = $number;
            $data['phone_setting_id'] = $res->id;
            $data['capabilities'] = json_encode([
                'voice'=>1,
                'SMS' => 0,
                'MMS' => 0,
                'fax' =>0
            ]);
        }elseif ($res->type == 'twilio'){
            $numbers = app('Twilio')->availablePhoneNumbers('HK')->local->read(
                array("voiceEnabled" => "true")
            );
            $number = app('Twilio')->incomingPhoneNumbers
                ->create(
                    array(
                        "phoneNumber" => $numbers[0]->phoneNumber
                    )
                );

        }elseif($res->type == 'plivo'){
            //获取手机号
            $phone = $this->plivoService->searchPhone();
            if($phone){
                //购买手机号
                $result = $this->plivoService->buy($phone['number']);
                if($result){
                    $data['friendly_name'] = $phone['number'];
                    $data['phone_number'] = $phone['number'];
                    $data['phone_setting_id'] = $res->id;
                }else{
                    return false;
                }
            }
        }
        $res = Phone::create($data);
    }
}
